package com.xinwei.leetcode;

/**
 * 搜索插入位置
 */
public class leetcode35 {
    // 暴力求法
    public static int searchInsert(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] >= target) {
                return i;
            }
        }
        return nums.length;
    }

    // 二分算法
    public static int searchInsert1(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int mid = (left + right) / 2;
        while (left <= right){
            if (nums[mid] < target) {
                left = mid + 1;
                mid = (left + right) / 2;
            }else if (nums[mid] == target){
                return mid;
            }else {
                right = mid - 1;
                mid = (left + right) / 2;
            }
        }
        return left;
    }

}
